<template>
  <!-- 购物车页面主容器 -->
  <div class="app-container" id="app">
    <!-- 快捷导航组件 -->
    <ShortCut></ShortCut>
    
    <!-- 顶部装饰图片 -->
    <div class="image-container">
      <img src="../assets/images/wp.png" class="wp">
      <img src="../assets/images/image.png" class="wp1">
    </div>
    <hr class="hr">
    
    <!-- 购物车主体 - 只在有商品时显示 -->
    <div class="main" v-if="currentCart && currentCart.goodsList && currentCart.goodsList.length > 0">
      <!-- 地址信息显示 -->
      <div class="address-list">
        <div 
          class="address-item" 
          v-for="(item, index) in uniqueAddresses" :key="index" :class="{ 'selected-address': selectedAddressIndex === index }" @click="selectAddress(index)" >
          <p>配送至：{{ item }}</p>
        </div>
      </div>
      
      <!-- 商品表格 -->
      <div class="table">
        <!-- 表格头部 -->
        <div class="thead">
          <div class="tr">
            <div class="th shangping">商品</div>
            <div class="th">单价</div>
            <div class="th num-th">数量</div>
            <div class="th">操作</div>
          </div>
        </div>
        
        <!-- 表格内容 -->
        <div class="tbody">
          <!-- 遍历购物车中的商品 -->
          <div class="tr" v-for="item in currentCart.goodsList" :key="item.id">
            <!-- 复选框 -->
            <div class="input"><input type="checkbox" v-model="item.isChecked" /></div>
            <!-- 商品信息 -->
            <div class="product-item">
              <img :src="item.imgSrc" :alt="item.name" class="product-img" />
              <div class="product-name">{{ item.name }}<br>{{item.color}}; {{ item.size }}</div>
            </div>
            <!-- 商品单价 -->
            <div class="price-item">¥{{ item.DiscountPrice || item.price }}</div>
            <!-- 数量控制 -->
            <div class="td">
              <div class="quantity-control">
                <button class="qty-btn" @click="decreaseQuantity(item)" :disabled="item.num <= 1">-</button>
                <span class="quantity">{{ item.num }}</span>
                <button class="qty-btn" @click="increaseQuantity(item)">+</button>
              </div>
            </div>
            <!-- 删除按钮 -->
            <div class="td">
              <button class="delete-btn" @click="removeItem(item)">删除</button>
            </div>
          </div>
        </div>
      </div>
      <br><br>
      
      <!-- 底部结算栏 -->
      <div class="checkout-bar">
        <!-- 全选复选框 -->
        <div class="select-all">
          <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
          <span>全选</span>
        </div>
        <!-- 商品数量和总价信息 -->
        <div class="total-info">
          <div class="selected-count">共 <span class="num">{{ totalQuantity }}</span> 件商品 </div>
          <div class="total-amount">
            总金额: <span class="amount">¥{{ totalAmount }}</span>
          </div>
        </div>
        <hr>
        <!-- 结算按钮 -->
        <button class="checkout-btn" @click="checkout" :disabled="selectedItems.length === 0">立即结算 </button>
      </div>
    </div>
    
    <!-- 空购物车状态 -->
    <div class="empty-cart" v-else>
      <div class="empty-icon">
        <!-- 空购物车图标 -->
        <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1.5">
          <circle cx="9" cy="21" r="1"></circle>
          <circle cx="20" cy="21" r="1"></circle>
          <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
        </svg>
      </div>
      <div class="empty-text">您的购物袋空空如也</div>
      <div class="empty-hint">快去挑选心仪的商品吧~</div>
      <!-- 去购物按钮 -->
      <button class="shopping-btn" @click="goShopping">去逛逛</button>
    </div>
    
    <!-- 页脚组件 -->
    <Footer></Footer>
  </div>
</template>
 
<script setup>
// 导入Vue相关功能
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import ShortCut from '@/components/common/ShortCut.vue'
import Footer from '@/components/common/Footer.vue'
 
// 初始化路由
const router = useRouter()
// 定义响应式数据
const cartData = ref([]) // 存储所有购物车数据
const currentCart = ref(null) // 当前用户的购物车
const selectedAddressIndex = ref(0) // 当前选中的地址索引
 
// 计算属性：获取所有唯一的地址
const uniqueAddresses = computed(() => {
  if (!currentCart.value || !currentCart.value.goodsList) return []
  
  const addresses = new Set()
  currentCart.value.goodsList.forEach(item => {
    if (item.address) {
      addresses.add(item.address)
    }
  })
  
  return Array.from(addresses)
})
 
// 计算属性：获取当前选中的地址
const selectedAddress = computed(() => {
  return uniqueAddresses.value[selectedAddressIndex.value] || ''
})
 
// 选择地址
const selectAddress = (index) => {
  selectedAddressIndex.value = index
}
 
// 计算属性：计算选中的商品总数
const totalQuantity = computed(() => {
  if (!currentCart.value || !currentCart.value.goodsList) return 0;
  return currentCart.value.goodsList.reduce((total, item) => {
    return total + (item.isChecked ? item.num : 0);
  }, 0);
});
 
// 获取当前登录用户名
const userName = sessionStorage.getItem('userName')
 
// 获取购物车数据
const fetchCartData = async () => {
  try {
    const response = await axios.get('http://localhost:3001/cartList')
    cartData.value = response.data
    
    // 查找当前用户的购物车
    currentCart.value = cartData.value.find(cart => cart.userName === userName)
    
    // 初始化选中状态
    if (currentCart.value && currentCart.value.goodsList) {
      currentCart.value.goodsList.forEach(item => {
        item.isChecked = item.isChecked || false
      })
    }
  } catch (error) {
    console.error('获取购物车数据失败:', error)
  }
}
 
// 组件挂载时获取购物车数据
onMounted(() => {
  fetchCartData()
})
 
// 计算属性：获取选中的商品
const selectedItems = computed(() => {
  if (!currentCart.value || !currentCart.value.goodsList) return []
  return currentCart.value.goodsList.filter(item => item.isChecked)
})
 
// 计算属性：计算选中商品的总金额
const totalAmount = computed(() => {
  return selectedItems.value.reduce((sum, item) => {
    return sum + (item.DiscountPrice || item.price) * item.num
  }, 0)
})
 
// 计算属性：全选/取消全选
const selectAll = computed({
  get() {
    if (!currentCart.value || !currentCart.value.goodsList) return false
    return currentCart.value.goodsList.every(item => item.isChecked)
  },
  set(value) {
    if (currentCart.value && currentCart.value.goodsList) {
      currentCart.value.goodsList.forEach(item => {
        item.isChecked = value
      })
    }
  }
})
 
// 增加商品数量
const increaseQuantity = async (item) => {
  item.num++
  await updateCartItem(item)
}
 
// 减少商品数量
const decreaseQuantity = async (item) => {
  if (item.num > 1) {
    item.num--
    await updateCartItem(item)
  }
}
 
// 更新购物车商品
const updateCartItem = async (item) => {
  try {
    await axios.patch(`http://localhost:3001/cartList/${currentCart.value.id}`, {
      goodsList: currentCart.value.goodsList
    })
  } catch (error) {
    console.error('更新购物车失败:', error)
  }
}
 
// 删除商品
const removeItem = async (item) => {
  if (!currentCart.value || !currentCart.value.goodsList) return
  
  const index = currentCart.value.goodsList.findIndex(i => i.id === item.id)
  if (index !== -1) {
    currentCart.value.goodsList.splice(index, 1)
    
    try {
      await axios.patch(`http://localhost:3001/cartList/${currentCart.value.id}`, {
        goodsList: currentCart.value.goodsList
      })
      fetchCartData() // 刷新数据
    } catch (error) {
      console.error('删除商品失败:', error)
    }
  }
}
 
// 结算功能
const checkout = async () => {
  if (selectedItems.value.length === 0) return;
  
  try {
    // 1. 创建订单数据
    const orderData = {
      id: Date.now().toString(), // 使用时间戳作为订单ID
      userName: userName,
      orderTime: new Date().toISOString(),
      status: 0,
      goodsList: selectedItems.value,
      totalAmount: totalAmount.value,
    };
 
    // 2. 发送到orderList
    await axios.post('http://localhost:3001/orderList', orderData);
    
    // 3. 从购物车中移除已结算商品
    currentCart.value.goodsList = currentCart.value.goodsList.filter(
      item => !item.isChecked
    );
    
    // 4. 更新购物车数据
    await axios.patch(`http://localhost:3001/cartList/${currentCart.value.id}`, {
      goodsList: currentCart.value.goodsList
    });
    
    // 5. 跳转到订单确认页
    router.push('/Cal');
  } catch (error) {
    console.error('结算失败:', error);
    alert('结算失败，请重试');
  }
};
 
// 去购物
const goShopping = () => {
  router.push('/home')
}
</script>
<style scoped>
/* 添加地址信息样式 */
.address-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}
 
.address-info h3 {
  margin-top: 0;
  color: #333;
}
 
.address-list {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
 
.address-item {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  background-color: white;
}
 

 


.empty-cart {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 30vh; /* 至少占视口高度的60% */
  text-align: center;
  padding: 20px;
  flex-direction: column;
}

.empty-content {
  max-width: 400px;
  width: 100%;
}

.empty-icon {
  margin-bottom: 20px;
}

.empty-text {
  font-size: 18px;
  color: #333;
  margin-bottom: 10px;
  font-weight: 500;
}

.empty-hint {
  font-size: 14px;
  color: #999;
  margin-bottom: 20px;
}

.shopping-btn {
  background: #f10180;
  color: white;
  border: none;
  padding: 10px  30px;
  font-size: 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
}

.shopping-btn:hover {
  background: #e00070;
}
/* 结算按钮 */
.checkout-btn {
  background: #f10180;
  color: white;
  width: 210px;
  height: 60px;
  border: none;
  font-size: 18px;
  margin-left: auto; /* 仅保留左auto实现右对齐 */
  display: block; /* 使margin auto生效 */
}
/* 总信息区域 - 右对齐 */
.total-info {
  display: flex;
  align-items: center;
  justify-content: flex-end; /* 右对齐关键属性 */
  gap: 20px; /* 元素间距 */
}

/* 数量显示 */
.selected-count {
  font-size: 14px;
  color: #666;
}

.selected-count .num {
  color: #f10180;
  font-weight: bold;
}

/* 总金额 */
.total-amount {
  font-size: 16px;
}

.total-amount .amount {
  color: #f10180;
  font-size: 18px;
  font-weight: bold;
}

/* 商品列样式 */
.shangping {
  width: 335px; /* 设置商品列固定宽度 */
  padding-left: 15px;
  color: #333;
  font-size: 16px;
}

.th th-pic{
      padding-left: 15px;
    width: 333px;
    color: #333;
    font-size: 16px;
}

/* 数量列调整 */
.quantity-control {
  width: 120px; /* 数量控制列宽度 */
  display: flex;
  justify-content: center;
}

/* 其他列宽度调整 */
.price-item {
  width: 100px; /* 单价列宽度 */
  color: #f10180;
  text-align: center;
   padding: 15px 0px 15px 15px;
}

.product-item{
  width: 335px;
    padding-left: 15px;
      display: flex;          /* 使用flex布局 */
  align-items: flex-start; /* 顶部对齐 */
  padding: 15px 0px 15px 15px;

}
/* 商品图片 */
.product-img {
  height: 74px;
  width: 74px;
  margin-right: 10px;
  flex-shrink: 0;
}
/* 操作列调整 */
.delete-btn {
  width: 80px; /* 操作列宽度 */
}

/* 商品名称 */
.product-name {
  font-size: 12px;
  width: 180px; /* 名称区域宽度 */
  max-height: 74px;
  line-height: 18px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
  margin: 0;
  padding: 0;
  text-align: left;
  word-break: break-word;
}
.hr {
height: 2px; /* 设置线条高度 */
background-color: #f3168a; /* 设置背景颜色 */
border: none; /* 去掉默认边框 */
}
.image-container {
  display: flex;
  align-items: center; /* 垂直居中 */
}

.wp {
  width: 20%;
  margin-left: 330px;
}

.wp1 {
  width: 40%;
 margin-left: 600px;
}
.empty-text {
      font-size: 16px;
      color: #333;
      margin-bottom: 20px;
    }
 
    .action-buttons {
      display: flex;
      justify-content: center;
    }
 
    .action-button {
      width: 100px;
      height:35px;
      font-size: 15px;
      padding: 5px 10px;
      margin: 0 10px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      text-align: center;
    }
 
    .buy-now {
      background-color: #ff4081;
      color: white;
      
    }
 
    .view-orders {
      background-color: white;
      color: #333;
      border: 1px solid #ccc;
    }
    
.app-container {
  padding-bottom: 300px;
  width: 100%;
  margin: 0 auto;
}

@media screen and (max-width: 800px) {
  .app-container {
    width: 600px;
  }
}

.app-container .banner-box {
  border-radius: 20px;
  overflow: hidden;
  margin-bottom: 10px;
}

.app-container .banner-box img {
  width: 100%;
}

.app-container .nav-box {
  background: #ddedec;
  height: 60px;
  border-radius: 10px;
  padding-left: 20px;
  display: flex;
  align-items: center;
}

.app-container .nav-box .my-nav {
  display: inline-block;
  background: #5fca71;
  border-radius: 5px;
  width: 90px;
  height: 35px;
  color: white;
  text-align: center;
  line-height: 35px;
  margin-right: 10px;
}

.breadcrumb {
  font-size: 16px;
  color: gray;
}

.table {
  width: 100%;
  text-align: left;
  border-radius: 2px 2px 0 0;
  border-collapse: separate;
  border-spacing: 0;
}

.th {
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  text-align: left;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
  transition: background 0.3s ease;
}

.th.num-th {
  flex: 1.5;
}

.th {
  text-align: center;
}

.th:nth-child(4),
.th:nth-child(5),
.th:nth-child(6),
.th:nth-child(7) {
  text-align: center;
}

.th.th-pic {
  flex: 1.3;
}

.th:nth-child(6) {
  flex: 1.3;
}

.td:nth-child(4) {
  flex: 3;
}

.th,
.td {
  position: relative;
  padding: 16px 16px;
  overflow-wrap: break-word;
  flex: 1;
}
.input{
  display: flex;
  justify-content: center;
   padding: 16px 8px;
  align-items: center;
}
.pick-td {
  font-size: 14px;
}

.main,
.empty {
  border: 1px solid #f0f0f0;
  margin-top: 10px;
      margin-right: auto;
    margin-left: auto;
    width: 960px;
}

.tr {
  display: flex;
  cursor: pointer;
  border-bottom: 1px solid #ebeef5;
}

.tr.active {
  background-color: #f5f7fa;
}

.td {
  display: flex;
  justify-content: center;
  align-items: center;
}

.table img {
  width: 74;
  height: 74;
}

button {
  outline: 0;
  box-shadow: none;
  color: #fff;
  background: #ffffff;
  border-color: #ffffff;
  color: #969292;
  background: #ffffff;
  border-color: #ffffff;
  line-height: 1.5715;
  position: relative;
  display: inline-block;
  font-weight: 400;
  white-space: nowrap;
  text-align: center;
  background-image: none;
  border: 1px solid transparent;
  box-shadow: 0 2px 0 rgb(0 0 0 / 2%);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  touch-action: manipulation;
  height: 32px;
  padding: 4px 15px;
  font-size: 14px;
  border-radius: 2px;
}

button.pay {
  background-color: #3f85ed;
  margin-left: 20px;
}

.bottom {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 20px;
  border: 1px solid #f0f0f0;
  border-top: none;
  padding-left: 20px;
}

.right-box {
  display: flex;
  align-items: center;
}

.check-all {
  cursor: pointer;
}

.price {
  color: hotpink;
  font-size: 30px;
  font-weight: 700;
}

.price-box {
  display: flex;
  align-items: center;
}

.empty {
  padding: 20px;
  text-align: center;
  font-size: 30px;
  color: #909399;
}

.my-input-number {
  display: flex !important;
}

.my-input-number button {
  height: 40px;
  color: #333;
  border: 1px solid #dcdfe6;
  background-color: #f5f7fa;
}

.my-input-number button:disabled {
  cursor: not-allowed !important;
}

.my-input-number .my-input__inner {
  height: 40px;
  width: 50px;
  padding: 0;
  border: none;
  border-top: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
}

.my-input-number {
  position: relative;
  display: inline-block;
  width: 140px;
  line-height: 38px;
}

.my-input-number span {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}

.my-input-number .my-input {
  display: block;
  position: relative;
  font-size: 14px;
  width: 100%;
}

.my-input-number .my-input__inner {
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  height: 40px;
  line-height: 40px;
  outline: none;
  padding: 0 15px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
  padding-left: 50px;
  padding-right: 50px;
  text-align: center;
}

.my-input-number .my-input-number__decrease,
.my-input-number .my-input-number__increase {
  position: absolute;
  z-index: 1;
  top: 1px;
  width: 40px;
  height: auto;
  text-align: center;
  background: #f5f7fa;
  color: #606266;
  cursor: pointer;
  font-size: 13px;
}

.my-input-number .my-input-number__decrease {
  left: 1px;
  border-radius: 4px 0 0 4px;
  border-right: 1px solid #dcdfe6;
}

.my-input-number .my-input-number__increase {
  right: 1px;
  border-radius: 0 4px 4px 0;
  border-left: 1px solid #dcdfe6;
}

.my-input-number .my-input-number__decrease.is-disabled,
.my-input-number .my-input-number__increase.is-disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}
</style>